<template>
  <div class="page">
    <div class="scroll-list">
      <block v-for="(item, index) in chatList" :key="item.msgId">
        <div v-if="item.timestamp" class="show-date">{{item.date}}</div>
        <div v-if="item.type==='custom'" class="row tips-text">
          <span>{{login.openId === item.senderId ? '你' : doctor.doctorName}}撤回了一条消息</span>
        </div>
        <div :class="{ 'row': true, 'row-self': login.openId === item.senderId, 'row-friend': login.openId !== item.senderId }" v-else>
          <div :class="{ 'head-self': login.openId === item.senderId, 'head-friend': login.openId !== item.senderId}">
            <img class="avatar" :src="login.openId === item.senderId ? login.avatar : doctor.avatar" />
          </div>
          <div>
            <div v-if="login.openId !== item.senderId" class="nick">{{doctor.doctorName}}</div>
            <div :class="{ 'message': true, 'msg-self': login.openId === item.senderId, 'msg-friend': login.openId !== item.senderId }">
              <span>{{item.content}}</span>
            </div>
          </div>
        </div>
      </block>
    </div>
    <div class="footer">
      <div class="row">
        <div class="input-box">
          <textarea class="text-area" placeholder-class="placeholder" show-confirm-bar="false" cursor-spacing="30" maxlength="500"
                    disable-default-padding="true" confirm-hold="true" hold-keyboard="true" auto-height="false" placeholder="输入信息"
                    @input="inputClick" v-model="content"></textarea>
        </div>
        <div class="send-btn" v-if="content !== ''">
          <span class="send-text" @tap="sendMessage()">发 送</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import config from "../../config";

export default {
  data() {
    return {
      socketOpen:false,
      content: '',      //接收返送内容
      login: {
        openId: '2023',
        name: '大猪蹄子',
        avatar: 'https://img2.baidu.com/it/u=1581320883,910100018&fm=253&app=53&size=w500&n=0&g=0n&f=jpeg?sec=1686045994&t=9135844131fa04a7ad00686d88c76752'
      },
      doctor:{
        doctorId:'',      //doctor的ID
        doctorName:'',          //doctor的Name
        avatar:''         //doctor的头像
      },
      chatList: []     //消息列表
    };
  },
  onShow() {
    this.initWebSocket();
    this.scrollToBottom();
  },
  onLoad(options) {
    console.log(options)
    if(options.user !== '')
      this.initUser(JSON.parse(options.user))
    else{
      this.initDoctor(JSON.parse(options.doctor))

    }
  },
  onUnload() {
    wx.closeSocket({
      success(res) {
        console.log("主动断开连接");
      }
    });
  },

  methods: {


    initWebSocket(){
      const openid=this.login.openId
  /*开启websocket服务*/
  wx.connectSocket({
    url: 'ws://127.0.0.1:8081/imserver/' + openid,
    success: () => {
      console.log('WebSocket连接打开成功');
      this.socketOpen = true;

      // 设置 WebSocket 事件监听
      wx.onSocketMessage((res) => {
        console.log('收到服务器消息:', res.data);
        const data=JSON.parse(res.data.toString())
        this.scrollToBottom()
        this.receiverUpdate(data);
      });

      wx.onSocketError((error) => {
        console.error('WebSocket错误:', error);
      });

      wx.onSocketClose((res) => {
        console.log('WebSocket连接已关闭:', res);
        this.socketOpen = false;
      });
    },
    fail: (error) => {
      console.error('WebSocket连接打开失败', error);
    },
  });
},

    sendMessage() {
      // 确保 WebSocket 连接已经打开
      wx.onSocketOpen(() => {
        console.log('WebSocket 连接已打开');
        this.socketOpen = true;
      });
        // 例：发送初始消息
        const initialMessage = {
          type: 'text',
          to: this.doctor.doctorId,
          content: this.content,
        };

        // 发送消息
        if (this.socketOpen) {
          wx.sendSocketMessage({
            data: JSON.stringify(initialMessage),
            success: () => {
              console.log('消息发送成功');
              this.sendClick()
            },
            fail: (res) => {
              console.log(res);
            },
          });

        } else {
          console.error('WebSocket连接未打开，无法发送消息');
        }

    },


    initDoctor(doctor){
      const user=JSON.parse(wx.getStorageSync("userInfo"))
      console.log(user)
      if(user != null){
        this.login=user
      }
      this.doctor=doctor
      const mesgInit=config.mesgInitUrl;
    wx.request({
      url:mesgInit,
      method:"POST",
      data:{
        openId:user.openId,
        doctorId:doctor.doctorId.toString()
      },
      success:(res)=>{
        console.log(res.data.data)
        this.chatList=res.data.data
      }
    })

    },

    initUser(index){
      console.log(index)
      const doctor=JSON.parse(wx.getStorageSync("doctorInfo"))
      if(doctor != null){
        this.login.openId=doctor.doctorId+''
        this.login.name=doctor.doctorName
        this.login.avatar=doctor.avatar
      }
      this.doctor.doctorId=index.openId
      this.doctor.doctorName=index.name
      this.doctor.avatar=index.avatar

      const mesgInit=config.mesgInitUrl;
      wx.request({
        url:mesgInit,
        method:"POST",
        data:{
          openId:index.openId,
          doctorId:doctor.doctorId.toString()
        },
        success:(res)=>{
          console.log(this.login)
          console.log(this.doctor)
          console.log(res.data.data)
          this.chatList=res.data.data
        }
      })
    },

    inputClick(e) {
      this.content = e.mp.detail.value;
    },
    // 将时间字符串转换为时间戳
    getTimeDifference(dateString1, dateString2) {
      const date1 = new Date(dateString1);
      const date2 = new Date(dateString2);

      // 获取时间戳并计算差值
      const timestamp1 = date1.getTime();
      const timestamp2 = date2.getTime();
      const difference = Math.abs(timestamp1 - timestamp2) / 60000;    //计算上一次发消息与此次消息的差值为多少分钟
      return difference;
    },


    receiverUpdate(data){
      const date = new Date();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hour = date.getHours();
      const minu = date.getMinutes();
      const now1 = month < 10 ? '0' + month : month;
      const now2 = day < 10 ? '0' + day : day;
      const preDate=wx.getStorageSync("timeTap")
      let msg=''
      if(this.getTimeDifference(preDate,date) > 5 ) {
        msg = {
          senderId: this.doctor.doctorId,
          receiverId: this.login.openId,
          name: this.doctor.name,
          content: data.text,
          date: now1 + '-' + now2 + ' ' + hour + ':' + minu
        };
      }
      else  {
          msg = {
            senderId: this.doctor.doctorId,
            receiverId: this.login.openId,
            name: this.doctor.name,
            content: data.text,
          };
      }
        wx.setStorage({
          key:"timeTap",
          data:date
        })
        this.chatList.push(msg);
    },
    sendClick() {
      const date = new Date();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hour = date.getHours();
      const minu = date.getMinutes();
      const now1 = month < 10 ? '0' + month : month;
      const now2 = day < 10 ? '0' + day : day;
      const preDate=wx.getStorageSync("timeTap")
      let msg=''
      if(this.getTimeDifference(preDate,date) > 5) {
          msg = {
          senderId: this.login.openId,
          receiverId:this.doctor.doctorId,
          name: this.login.name,
          content: this.content,
          date: now1 + '-' + now2 + ' ' + hour + ':' + minu
        };
      }
      else  {
          msg = {
          senderId: this.login.openId,
          receiverId:this.doctor.doctorId,
          name: this.login.name,
          content: this.content
        };
      }
      wx.setStorage({
        key:"timeTap",
        data:date
      })
      if(this.chatList != null)
        this.chatList.push(msg)
       else{
        let arr=[]
        arr.push(msg)
        this.chatList=arr
      }
      this.scrollToBottom();
      this.content = '';
    },


    scrollToBottom() {
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 200000,
          duration: 3
        });
      }, 600)
    },
  }
};
</script>

<style scoped>
page {
  background-color: #f1f1f1;
}

.scroll-list {
  padding-bottom: 60px;
}

/* 显示时间 */
.show-date {
  text-align: center;
  font-size: 12px;
  padding: 7.5px 0;
  color: gray;
}

/* 每行对话样式 */
.row {
  display: flex;
  flex-direction: row;
  padding: 10px;
}

/* 提示信息 */
.tips-text {
  text-align: center;
  justify-content: center;
  font-size: 14px;
  color: gray;
}

.row-self {
  flex-direction: row-reverse;
}

/* 头像 */
.head-self {
  margin-left: 10px;
}

.head-friend {
  margin-right: 10px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  overflow: hidden;
}

.nick {
  color: gray;
  font-size: 12px;
  margin-bottom: 7.5px;
}

/* 消息内容 */
.message {
  background-color: white;
  font-size: 15px;
  padding: 10px;
  display: flex;
  align-items: center;
  line-height: 22.5px;
}

.msg-self {
  border-top-left-radius: 15px;
  border-bottom-right-radius: 15px;
  color: #434343;
  background-image: linear-gradient(to right, #33ccff, #B0E2FF);
}

.msg-friend {
  border-top-right-radius: 15px;
  border-bottom-left-radius: 15px;
  color: #ffffff;
  background-image: linear-gradient(to right, #ff9933, #ff6633);
}

/* 以下为输入框样式 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 9;
  background-color: white;
  border-top: 0.5px solid #f1f1f1;
}

.input-box {
  flex: 2.5;
  border: 0.5px solid #f1f1f1;
  border-radius: 5px;
}

.send-btn {
  flex: 0.5;
  text-align: center;
  margin-left: 5px;
  color: white;
  margin-top: 5px;
}

.send-text {
  background-color: #FF6347;
  font-size: 15px;
  border-radius: 5px;
  padding: 6px 10px;
}

.text-area {
  max-height: 90px;
  width: 98%;
  padding: 7.5px 5px;
  font-size: 15px;
}

.placeholder {
  font-size: 15px;
}

/* 隐藏滚动条 */
::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
  color: transparent;
}

</style>
